<template>
  <div class="app-container">
    <!-- v-permission="['data:tenant:read']"
      v-permission="['data:tenant:create']"
      v-permission="['data:tenant:update']"
      v-permission="['data:tenant:delete']" -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline filter">
      <el-form-item v-if="this.$store.state.user.fsiteLevel==3" label="客户名称">
        <el-input
        disabled
        v-model.trim="listQuery.fsiteName"
        clearable
        class="filter-item"
        placeholder="请输入客户名称"
      />
      </el-form-item>
      <el-form-item v-else label="客户名称">
        <el-input
        v-model.trim="listQuery.fsiteName"
        clearable
        class="filter-item"
        placeholder="请输入客户名称"
      />
      </el-form-item>
      <el-form-item v-if="this.$store.state.user.fsiteLevel==3" label="所属地区">
         <el-select
        disabled
        v-model="listQuery.fsiteParent"
        clearable
        filterable
        class="filter-item"
        placeholder="请选择所属地区"
      >
        <el-option
          v-for="item in fsiteNoBelongOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item v-else label="所属地区">
         <el-select
        v-model="listQuery.fsiteParent"
        clearable
        filterable
        class="filter-item"
        placeholder="请选择所属地区"
      >
        <el-option
          v-for="item in fsiteNoBelongOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item>
         <el-button
         round size="medium"
        class="filter-item"
        :style="{background:buttonColor.lookup,color:buttonColor.color}"
        @click="handleFilter"
      >查找</el-button
      >
      <el-button
      round size="medium"
        class="filter-item"
        :style="{background:buttonColor.add ,color:buttonColor.color}"
        @click="handleCreate"
      >添加</el-button
      >
      </el-form-item>
      </el-form>
      <!--<el-select v-model="listQuery.fsiteLevel" clearable filterable class="filter-item" placeholder="请选择地区类型">
        <el-option v-for="(key, value) in siteTypeMap" :key="key" :label="key" :value="value"/>
      </el-select>-->
      <!--<el-input v-model.trim="listQuery.fsiteLevel" clearable class="filter-item" style="width: 200px;" placeholder="请输入地区类型"/>-->

    <!-- 查询结果 -->
    <el-table
      :height="buttonColor.clientHeight"
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      :header-cell-style="tableColor"
    >
     <el-table-column align="center" :width="buttonColor.operationTwo" label="操作" class-name="small-padding">
        <template slot-scope="scope">
           <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
            <img src="../../../public/images/edit.png" />
            编辑
          </div>
          <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
            <img src="../../../public/images/del.png" />
            删除
          </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :width="buttonColor.line"
        :index="indexMethod"
        align="center"
        label="序"
        type="index"
      />
      <el-table-column :width="buttonColor.billno" align="left" label="客户编号" prop="fsiteNo" />
      <el-table-column align="left" label="客户名称" prop="fsiteName" width="180" />
      <el-table-column
        :formatter="formatSite"
        align="left"
        label="所属地区"
        prop="fsiteParent"
      />
      <el-table-column :width="buttonColor.name" align="left" label="联系人" prop="flinkMan" />
      <el-table-column width="120" align="left" label="手机" prop="fphone" />
      <el-table-column :width="buttonColor.name" :formatter="formatfengineer" align="left" label="工程师" prop="fengineer" />
      <el-table-column :width="buttonColor.state" align="left" label="客户状态" prop="fsiteState">
         <template slot-scope="scope">
          <span :style="{color:buttonColor.statedisable}" v-if="scope.row.fsiteState==0">{{ scope.row.fsiteState | statusFilter }}</span>
          <span :style="{color:buttonColor.statestart}" v-else>{{ scope.row.fsiteState | statusFilter }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      width="auto"
      top="0vh"
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
    >
    <template slot="title">
      <div :style="titleColor">{{textMap[dialogStatus]}}</div>
    </template>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="auto"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="客户编号" prop="fsiteNo">
              <el-input
                v-model="dataForm.fsiteNo"
                :disabled="dialogStatus == 'update'"
                type="number"
              /><!-- oninput="value=value.replace(/[^\d]/g,'')"-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="required"
              label="客户名称"
              prop="fsiteName"
            >
              <el-input v-model="dataForm.fsiteName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="所属地区"
              prop="fsiteParent"
            >
              <el-select
                v-model="dataForm.fsiteParent"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="el-form-item-small"
              label="地区类型"
              prop="fsiteLevel"
            >
              <el-select
              :disabled='true'
                v-model="dataForm.fsiteLevel"
                class="filter-item"
                placeholder="请选择地区类型"
              >
                <el-option
                  v-for="(key, value) in siteTypeMap"
                  :key="key"
                  :label="key"
                  :value="value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="纬度" prop="fsiteL">
              <el-input v-model="dataForm.fsiteL" @focus="clickMap" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="经度" prop="fsiteD">
              <el-input v-model="dataForm.fsiteD" @focus="clickMap" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="flinkMan">
              <el-input v-model="dataForm.flinkMan" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机" prop="fphone">
              <el-input v-model="dataForm.fphone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="电话" prop="ftelno">
              <el-input v-model="dataForm.ftelno" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="femail">
              <el-input v-model="dataForm.femail" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工程师" prop="fengineer">
              <el-select clearable filterable v-model="dataForm.fengineer" class="filter-item" placeholder="请选择工程师">
                <el-option
                v-for="item in getListfengineer"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              class="el-form-item-small"
              label="状态"
              prop="fsiteState"
            >
              <el-select
                v-model="dataForm.fsiteState"
                class="filter-item"
                placeholder="请选择状态"
              >
                <el-option
                  v-for="(key, value) in statusMap"
                  :key="key"
                  :label="key"
                  :value="value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              class="el-form-item-small"
              label="客户行业"
              prop="fsiteType"
            >
              <el-select
                v-model="dataForm.fsiteType"
                class="filter-item"
                placeholder="请选择客户行业"
              >
                <el-option
                  v-for="item in fsiteTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="12">
             <el-form-item
              label="课程表"
              prop="fcourseflag"
            >
              <el-checkbox-group v-model="fcourseflag">
                <el-checkbox label="是否启用课程表" name="fcourseflag"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
            <el-col :span="24">
            <el-form-item class="text" style="width:100%" label="3D链接" prop="fimage3d">
              <el-input v-model="dataForm.fimage3d" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              v-show="dataForm.fsiteLevel === '3'"
              label="学校图片(2M内)"
              prop="fimage"
              style="width: 320px"
            >
              <!--<el-input v-model="dataForm.fimage"/>-->
              <el-upload
                v-model="dataForm.fimage"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :action="uploadPath"
                :data="formdata2(dataForm.fsiteNo)"
                class="avatar-uploader"
              >
                <img
                  v-if="dataForm.fimage"
                  :src="dataForm.fimage"
                  class="avatar"
                >
                <i v-else class="el-icon-plus avatar-uploader-icon" />
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <!--<el-form-item label="操作员" prop="foperator">
          <el-input v-model="dataForm.foperator"/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          round
          v-if="dialogStatus == 'create'"
          :style="{background:buttonColor.confirm,color:buttonColor.color}"
          @click="createData"
        >确定</el-button
        >
        <el-button round v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible2"
      fullscreen
      width="1200px"
      height="800px"
      style="width: 100%; height: 80%; padding-top: 0px"
    >
    <template slot="title">
      <div :style="titleColor">百度地图</div>
    </template>
      <div
        slot="title"
        align="right"
        style="margin-top: 10px; margin-right: 30px"
      >
        <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible2 = false">取消</el-button>
        <el-button round :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="setLatLng">确定</el-button>
      </div>
      <cmap
        :center="dataForm.fsiteParent"
        :keyword="dataForm.fsiteName"
        :value="dialogFormVisible2"
        style="margin-top: 0px; width: 100%"
        @transfer="getPoint"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listArea,
  createArea,
  updateArea,
  deleteArea,
  fsiteOptionsByLevel,
  getListArea
} from '@/api/area'
import moment from 'moment'
import Pagination from '@/components/Pagination'
import { uploadPath } from '@/api/room'
import cmap from './baiduMap'
import { tableColor,titleColor,buttonColor } from '@/filters/index'

const siteTypeMap = {
  0: '省',
  1: '市',
  2: '区',
  3: '学校'
}

const statusMap = {
  0: '禁用',
  1: '启用'
}
const fsiteTypeMap = {
  1: '教育' ,
  2:'零售'
}

const fexecweekOptions = {
  1: "周一",
  2: "周二",
  3: "周三",
  4: "周四",
  5: "周五",
  6: "周六",
  7: "周日",
};

export default {
  name: 'Area',
  components: { Pagination, cmap },
  filters: {
    siteTypeFilter(type) {
      return siteTypeMap[type]
    },
    statusFilter(type) {
      return statusMap[type]
    },

    fsiteTypeFilter(type) {
      return fsiteTypeMap[type]
    }
  },
  data() {
    return {
      getListfengineer:null,
      uploadPath,
      list: null,
      total: 0,
      fsiteNoBelongOptions: null,
      center: '北京',
      lat: 0,
      lng: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteName: undefined,
        fsiteParent: undefined,
        fengineer: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      siteTypeMap,
      statusMap,
      fsiteTypeMap,
      fexecweekOptions,
      fsiteTypeList:[
        { value:1,label: '教育'},
        { value:2,label:'零售'},
      ],
      dataForm: {
        id: undefined,
        fsiteNo: undefined,
        fimage: undefined,
        fimage3d: undefined,
        fsiteName: undefined,
        fsiteParent: undefined,
        fsiteLevel: undefined,
        fsiteL: undefined,
        fsiteD: undefined,
        flinkMan: undefined,
        fphone: undefined,
        ftelno: undefined,
        femail: undefined,
        fengineer: undefined,
        fsiteState: undefined,
        fupddate: undefined,
        foperator: undefined,
        fsiteType: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fcourseflag: undefined,
        fexecweekList: []
      },
      fcourseflag: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableColor: tableColor,
      titleColor: titleColor,
      buttonColor:buttonColor,
      rules: {
        fsiteNo: [
          { required: true, message: '客户编号不能为空', trigger: 'blur' }
        ],
        fsiteName: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        fsiteParent: [
          { required: true, message: '所属地区不能为空', trigger: 'blur' }
        ],
        fsiteLevel: [
          { required: true, message: '地区类型不能为空', trigger: 'blur' }
        ],
        fsiteL: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
        fsiteD: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
        fsiteState: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      permissionDialogFormVisible: false,
      systemPermissions: null,
      assignedPermissions: null,
      permissionForm: {
        roleId: undefined,
        permIds: []
      }
    }
  },
  created() {
    if(this.$store.state.user.fsiteLevel==3) {
      this.listQuery.fsiteName = this.$store.state.user.fsiteName
    }
    this.getList()
    fsiteOptionsByLevel(2)
      .then((response) => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })
      getListArea({flag:8,arg1:13})
      .then(response => {
        this.getListfengineer = response.data.data.list.filter(
          item=>{
            item.value = item.value.toString()
            return item
        })
      })
      .catch(() => {
        this.getListfengineer = []
      })
  },
  methods: {
    formatfengineer: function(row, column) {
      if(this.getListfengineer){
        for (let i = 0; i < this.getListfengineer.length; i++) {
        if (row.fengineer === this.getListfengineer[i].value) {
          return this.getListfengineer[i].label
        }
      }
      return ''
      }else{
      return ''
      }
    },
    handleAvatarSuccess(res, file) {
      // this.dataForm.fimage = URL.createObjectURL(file.raw)
      this.dataForm.fimage = res.data
      const time = new Date().getTime()
      this.dataForm.fimage = `${this.dataForm.fimage}?time=${time}`
    },
    formdata2: function(fsiteno) {
      // const formdata = new FormData()
      // formdata.append('fpointno', '123456')
      return { ftype: '2', fsiteno: fsiteno }
    },
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isLt2M // isJPG &&
    },
    formatStatus: function(row, column) {
      return row.fsiteState === 1 ? '启用' : '禁用'
    },
    dateFormat(row, column) {
      const date = row[column.property]
      if (date === undefined) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatSite: function(row, column) {
      if(this.fsiteNoBelongOptions){
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
        if (row.fsiteParent === this.fsiteNoBelongOptions[i].value) {
          return this.fsiteNoBelongOptions[i].label
        }
      }
       return ''
      }else{
        return ''
      }

    },
    getList() {
      this.listLoading = true
      this.listQuery.fsiteLevel = 3
      listArea(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        fsiteNo: undefined,
        fimage: undefined,
        fimage3d: undefined,
        fsiteName: undefined,
        fsiteParent: undefined,
        fsiteLevel: undefined,
        fsiteL: undefined,
        fsiteD: undefined,
        flinkMan: undefined,
        fphone: undefined,
        ftelno: undefined,
        femail: undefined,
        fengineer: undefined,
        fsiteState: undefined,
        fupddate: undefined,
        foperator: undefined,
        fsiteType: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fcourseflag: undefined,
        fexecweekList: []
      }
      this.fcourseflag = []
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.dataForm.fsiteState = '1'
      this.dataForm.fsiteLevel = '3'
      this.dataForm.fsiteType = 1
      if(this.fsiteNoBelongOptions.length>0){
      this.dataForm.fsiteParent = this.fsiteNoBelongOptions[1].value
      }
      if(this.getListfengineer.length>0){
      this.dataForm.fenginee = this.getListfengineer[0].value
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    clickMap() {
      // this.resetForm()
      this.dialogFormVisible2 = true
      this.lat = 0
      this.lng = 0
      // this.dataForm.fsiteState = '1'
      // this.$nextTick(() => {
      //   this.$refs['dataForm'].clearValidate()
      // })
    },
    getPoint(point) {
      this.lat = point.lat
      this.lng = point.lng
    },
    setLatLng() {
      this.dialogFormVisible2 = false
      this.dataForm.fsiteL = this.lat
      this.dataForm.fsiteD = this.lng
      this.$refs['dataForm'].validateField('fsiteL')
      this.$refs['dataForm'].validateField('fsiteD')
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator=this.$store.state.user.id
          this.dataForm.fupddate=new Date()
          this.dataForm.fcourseflag=this.fcourseflag.length
          createArea(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dataForm.fsiteLevel = row.fsiteLevel.toString()
      this.dataForm.fsiteState = row.fsiteState.toString()
      this.dialogStatus = 'update';
      this.dialogFormVisible = true
       if(row.fcourseflag == 0){
        this.fcourseflag = []
      }else{
        this.fcourseflag = ['是否启用课程表']
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator=this.$store.state.user.id
          this.dataForm.fupddate=new Date()
          this.dataForm.fcourseflag=this.fcourseflag.length
          updateArea(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.fsiteNo === this.dataForm.fsiteNo) {
                  const index = this.list.indexOf(v)
                  this.dataForm.fsiteState=parseInt(this.dataForm.fsiteState)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.msg
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否删除该资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteArea(row)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    selectAll() {
      if (this.dataForm.fexecweekList.length < 7) {
        this.dataForm.fexecweekList = [];
        for (var option in fexecweekOptions) {
          this.dataForm.fexecweekList.push(option);
        }
      } else {
        this.dataForm.fexecweekList = [];
      }
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/*处理input type = number的上下箭头*/
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>
